package com.hjx.windowtool.bk.dibaqu.server;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.hjx.windowtool.util.StrUtil;

@Service
public class BookInfoService {
	@Autowired
	private BookInfoRepository bookInfoRepository;
	@Autowired
	BookChapterRepository bookChapterRepository;
	@PersistenceContext
    EntityManager entityManager;
	
	public Page<BookInfo> findBook(int start,int max,String title,String author,Integer count){
		
		Specification<BookInfo> example=new Specification<BookInfo>() {
			private static final long serialVersionUID = 1L;
			@Override
			public Predicate toPredicate(Root<BookInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list=new ArrayList<Predicate>();
				if (!StrUtil.isEmpty(title)) {
					list.add(cb.and(cb.like(root.get("title"), "%"+title+"%")));
				}
				if(!StrUtil.isEmpty(author)) {
					list.add(cb.and(cb.like(root.get("author"), "%"+author+"%")));
				}
				if(count!=null) {
					list.add(cb.and(cb.ge(root.get("chapterCount"), count)));
				}
				return cb.and(list.toArray(new Predicate[list.size()]));
			}
		};
		Page<BookInfo> page = bookInfoRepository.findAll(example, PageRequest.of(start, max));
		System.out.println(page.getTotalElements());
		return page;
	}
	@Transactional
	public BookInfo findBookById(Long id) {
		return bookInfoRepository.findById(id).get();
	}
	@Transactional
	public List<BookChapter> findBookChapterById(Long id) {
		BookInfo bookInfo = bookInfoRepository.findById(id).get();
		if (bookInfo==null) {
			return new ArrayList<>();
		}
		return bookChapterRepository.findByBook(bookInfo);
	}
	@Transactional
	public BookInfo saveBook(BookInfo book) {
		BookInfo info = bookInfoRepository.save(book);
		bookChapterRepository.deleteByBook(info);
		List<BookChapter> list = book.getChapters();
		for (BookChapter bookChapter : list) {
			bookChapter.setBook(info);
			bookChapterRepository.save(bookChapter);
		}
		return info;
	}
}
